package ee.ut.maxorato_macobo.oop.mud.items;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.Map.Entry;

public class ItemProcessorPool {
	private static TreeMap<Long, ItemBase> itemList = new TreeMap<Long, ItemBase>();
	private static ArrayList<ItemBase> removeList = new ArrayList<ItemBase>();
	private static int mapUseCount = 0;
	
	public static boolean registerItem(ItemBase item) {
		if(itemList.containsKey(item.getItemIndex())) return false;
		
		itemList.put(item.getItemIndex(), item);
		return true;
	}
	
	public static boolean unregisterItem(ItemBase item) {
		if(!itemList.containsKey(item.getItemIndex())) return false;
		
		if(mapUseCount > 0) removeList.add(item);
		else itemList.remove(item.getItemIndex());
		return true;
	}
	
	public static void processRemoveList() {
		if(mapUseCount > 0) return;
		
		for(ItemBase item : removeList) {
			unregisterItem(item);
		}
	}
	
	public static void beginUsingMap() {
		mapUseCount++;
	}
	
	public static void endUsingMap() {
		if(mapUseCount > 0) {
			mapUseCount--;
		}
		
		if(mapUseCount == 0) {
			processRemoveList();
		}
	}
	
	public static ItemBase findItem(long itemIndex) {
		return itemList.get(itemIndex);
	}
	
	public static TreeMap<Long, ItemBase> getItemList() {
		return itemList;
	}
	
	public static void processTick() {
		beginUsingMap();
		
		Iterator<Entry<Long, ItemBase>> it = itemList.entrySet().iterator();
		
		while(it.hasNext()) {
			Entry<Long, ItemBase> entry = it.next();
			
			entry.getValue().processTick();
		}
		
		endUsingMap();
	}
	
	private ItemProcessorPool() {
		
	}
}
